import {
  getInspectItemByPage,
  addInspectItem,
  updateInspectItem,
  delInspectItem,
  exportInspectItem,
  uploadInspectFile,
  delInspectFile,
  getCheckItem,
  getCheckDesc,
  exportInspectFile,
  generateMaintenanceInfoByInspect,
  getInspectFileByPage,
} from '@/services/device/inspectItem';
import { PlusOutlined, UploadOutlined } from '@ant-design/icons';
import { tableSearchPublicConfig } from '@/utils/filterUtils';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  Button,
  Card,
  Descriptions,
  Form,
  Input,
  message,
  Modal,
  Select,
  Space,
  Tree,
  Upload,
} from 'antd';
import { sortTran, filterTran } from '@/utils/requestUtil';
import React, { useEffect, useRef, useState } from 'react';
import { ModalForm, ProFormItem, ProFormSelect, ProFormText } from '@ant-design/pro-components';
import { Ellipsis } from '@/components/Ellipsis';
const InspectItem: React.FC<{}> = (props) => {
  const actionRef = useRef<ActionType>();
  const actionRef1 = useRef<ActionType>();
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [modalVisit1, setModalVisit1] = useState(false); // 新建和编辑提示框
  const [modalVisit2, setModalVisit2] = useState(false); // 新建和编辑提示框
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable
  const [formTitle, setFormTitle] = useState('新建'); //
  const [formTitle1, setFormTitle1] = useState('新建'); //
  const [createOrUpdate, setCreateOrUpdate] = useState(false); //编辑框的disable
  const [itemId, setItemId] = useState('');
  const [file, setFile] = useState();
  const [formTitle_file, setFormTitle_file] = useState(''); //
  const [modalVisit_file, setModalVisit_file] = useState(false); // 上传附件
  const actionRef_file = useRef<ActionType>();
  const [confirmLoading_file, setConfirmLoading_file] = useState(false);
  const [modalVisit4, setModalVisit4] = useState(false); // 上传附件
  const [confirmLoading4, setConfirmLoading4] = useState(false);
  const [formTitle4, setFormTitle4] = useState('新建'); //
  const [currentTaskId, setCurrentTaskId] = useState();
  const [inspectItem, setInspectItem] = useState();
  const [resultFlag, setResultFlag] = useState();
  const [checkOptions, setCheckOptions] = useState([]);
  const [descOptions, setDescOptions] = useState([]);
  const [fileList, setFileList] = useState(); //文件上传列表
  const [form] = Form.useForm();
  const ref = useRef(null);
  // let fileInfo = {
  //   inspectitemId: '',
  //   // multipartFile: '',
  //   fileName: '',
  //   memo: '11',
  // };
  const ref1 = useRef(null);
  useEffect(() => {
    setCurrentTaskId(props.taskId ? props.taskId : '');
  }, []);

  const handleMemoChange = async (value) => {
    console.log(value);
    const res = await getCheckDesc(value);
    console.log('检查描述', res);
    const temp: any[] = [];
    temp.push({ label: res.messae, value: res.message });
    setDescOptions(temp);
    form.setFieldsValue({
      itemName: value,
      itemDesc: res.message,
    });
  };

  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 80,
      align: 'center',
      sorter: true,
    },
    {
      title: '唯一标识',
      dataIndex: 'uniqueIdentifier',
      hideInTable: true,
      align: 'center',
      sorter: true,

      search: false,
    },
    {
      title: '巡检任务号',
      dataIndex: 'taskId',
      align: 'center',
      sorter: true,
    },
    {
      title: '检查项目',
      dataIndex: 'itemName',
      align: 'center',
      sorter: true,

      ellipsis: true,
    },
    {
      title: '检查描述',
      dataIndex: 'itemDesc',
      align: 'center',
      sorter: true,

      ellipsis: true,
    },

    {
      title: '检查结果', // 正常/异常/待检查
      dataIndex: 'itemResult',
      align: 'center',
      sorter: true,

      render: (text: any) => (
        <div>{text === 'true' ? '正常' : text === 'false' ? '异常' : '待检查'}</div>
      ),
    },
    {
      title: '故障描述',
      dataIndex: 'faultDesc',
      align: 'center',
      sorter: true,

      search: false,
    },
    {
      title: '备注',
      dataIndex: 'notes',
      hideInTable: true,
      align: 'center',
      sorter: true,

      search: false,
    },
    {
      title: '创建日期', //表头显示的名称
      search: false,
      dataIndex: 'createTime',
      hideInTable: true,
      align: 'center',
      sorter: true,
    },
    {
      title: '创建人', //表头显示的名称
      search: false,
      dataIndex: 'createName',
      hideInTable: true,
      align: 'center',
      sorter: true,
    },
    {
      title: '处理人',
      dataIndex: 'assignedTo',
      hideInTable: true,
      align: 'center',
      sorter: true,

      search: false,
    },
    {
      title: '附件',
      dataIndex: 'attachment',
      hideInTable: true,
      align: 'center',
      sorter: true,

      search: false,
    },
    {
      title: '设备编号',
      dataIndex: 'deviceId',
      hideInTable: true,
      align: 'center',
      sorter: true,

      search: false,
    },
    {
      title: '问题描述',
      dataIndex: 'issue',
      hideInTable: true,
      align: 'center',
      sorter: true,

      search: false,
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      align: 'center',

      render: (text, record, _, action) => [
        <a
          key="editKey"
          onClick={() => {
            setModalVisit_file(true);
            setModalVisit(true);
            setCreateOrUpdate(false);
            setFormTitle('填报');
            form.setFieldsValue({
              assignedTo: record.assignedTo,
              attachment: record.attachment,
              deviceId: record.deviceId,
              issue: record.issue,
              faultDesc: record.faultDesc,
              itemDesc: record.itemDesc,
              itemName: record.itemName,
              itemResult: record.itemResult,
              notes: record.notes,
              taskId: record.taskId,
              uniqueIdentifier: record.uniqueIdentifier,
              id: record.id,
            });
          }}
        >
          填报
        </a>,
        <a
          key="uploadFile"
          onClick={() => {
            setInspectItem(record);
            setModalVisit1(true);
            actionRef1.current?.reload();
          }}
        >
          查看附件
        </a>,

        <a
          key="deleteKey"
          onClick={() => {
            Modal.confirm({
              title: '删除',
              content: '确定要删除吗',
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                await delInspectItem({ id: record.id });
                actionRef.current.reload();
              },
            });
          }}
        >
          删除
        </a>,
      ],
    },
  ];
  /* 附件表格列表配置 */
  const columns1: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 80,
      align: 'center',
      sorter: true,
    },
    {
      title: '检查项目',
      dataIndex: 'memo',
      align: 'center',
      sorter: true,
    },
    {
      title: '巡检任务号',
      dataIndex: 'taskId',
      align: 'center',
      sorter: true,
    },
    {
      title: '文件名称',
      dataIndex: 'fileName',
      align: 'center',
      sorter: true,
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      align: 'center',

      render: (text, record, _, action) => [
        <a
          key="editKey"
          onClick={() => {
            if (record.fileUrl) {
              window.open(record.fileUrl);
            }
          }}
        >
          预览下载
        </a>,
        <a
          key="deleteKey"
          onClick={() => {
            Modal.confirm({
              title: '删除',
              content: '确定要删除吗',
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                await delInspectFile({ id: record.id });
                actionRef1.current?.reload();
              },
            });
          }}
        >
          删除
        </a>,
      ],
    },
  ];
  const handleSubmit = async (values) => {
    setConfirmLoading(true);
    console.log('提交的新建数据', values);
    if (formTitle == '新建') {
      const result = await addInspectItem(values);
      if (result != null) {
        message.success('添加成功');
      }
    } else {
      await updateInspectItem(values);
    }
    if (values.itemResult == false) {
      await generateMaintenanceInfoByInspect(values);
    }
    setConfirmLoading(false);
    setModalVisit(false);
    actionRef.current?.reload();
  };

  // /* 在文件上传之前进行检验 */
  const handleBeforeUpload = (info: any) => {
    // console.log('在文件上传之前进行检验', info);
    // //检验文件大小
    // if (info.size) {
    //   const isLt = info.size / 1024 / 1024 < 1000;
    //   if (!isLt) {
    //     alert(`上传文件大小不能超过 ${1} GB!`);
    //     return false;
    //   } else {
    //     //验证通过
    //   }
    // }
    //检验成功
    return false; //这里必须要返回false，来阻止原生的组件的默认action行为，不然会显示存储错误的信息
  };

  // /* 文件列表改变时，文件上传时触发 */
  const onFilesChange = (info: any) => {
    console.log('111', info);
    setFileList(info.fileList);
  };

  // /* 上传附件 */
  const addErrorFile = async () => {
    form
      .validateFields()
      .then(async () => {
        if (fileList == undefined) message.error('请上传文件！');
        if (fileList[0].size / 1024 / 1024 < 100) {
          const res = form.getFieldsValue();
          res.inspectitemId = res.taskId;
          delete res.taskId;
          const formData = new FormData();
          res.file.fileList.map((file: any) => {
            formData.append('file', file.originFileObj);
          });
          res.memo = inspectItem?.itemName;
          res.fileName = res.file.file.name;
          res.file = formData;
          console.log('附件上传参数：', res);
          const result = await uploadInspectFile(res);
          if (result != null) {
            message.success('异常新增成功');
          }
          setModalVisit2(false);
          actionRef1.current?.reload();
        } else {
          message.info('文件大小不能超过100MB!');
          return;
        }
      })
      .catch(() => {
        message.error('上传附件失败！');
      });
  };
  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <ProTable
        headerTitle="巡检计划任务明细查询"
        actionRef={actionRef} //用于触发刷新操作等，看api
        rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
        formRef={ref}
        search={false}
        toolBarRender={(action, { selectedRows }) => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              setCreateOrUpdate(false);
              setFormTitle('新建');
              form.resetFields();
              setModalVisit(true);
            }}
            type="primary"
          >
            新建
          </Button>,
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              const filters = filterTran(ref.current.getFieldsValue());
              exportInspectItem({
                current: 1,
                pageSize: 5000,
                filters: filters,
              }).then((res) => {
                const aLink = document.createElement('a');
                document.body.appendChild(aLink);
                aLink.style.display = 'none';
                aLink.href = window.URL.createObjectURL(res);
                aLink.setAttribute('download', `InspectItem.xlsx`);
                aLink.click();
                document.body.removeChild(aLink);
              });
            }}
            type="primary"
          >
            导出
          </Button>,
        ]}
        pagination={{
          defaultCurrent: 1,
          defaultPageSize: 100,
          showSizeChanger: true,
          pageSizeOptions: ['100', '500', '1000'],
        }}
        request={async (params = {}, sort, filter) => {
          const paramsFilter = { ...params, taskId: currentTaskId };
          const sorters = sortTran(sort);
          const filters = filterTran(paramsFilter);
          const result = await getInspectItemByPage({
            ...params,
            sorters: sorters,
            filters: filters,
          });
          const tableinfo: any[] = [];
          result.data.content.map((item: any, index: number) => {
            if (item != null && item.taskId == currentTaskId) {
              tableinfo.push(item);
            }
          });
          const res = await getCheckItem(null);
          const temp: any[] = [];
          console.log('获得的项目数据', result);
          res.data.map((item: any, index: number) => {
            if (item != null) {
              temp.push({ label: item, value: item });
            }
          });
          setCheckOptions(temp);

          return {
            data: tableinfo,
            total: result.data.totalElements,
            success: result.success,
          };
        }}
        columns={columns}
        scroll={{ x: 1000, y: 350 }}
        rowSelection={{}}
      />

      <ModalForm
        visible={modalVisit}
        title={formTitle}
        form={form}
        onFinish={handleSubmit}
        modalProps={{
          destroyOnClose: true,
          onCancel: () => {
            setModalVisit(false);
          },
        }}
      >
        <ProFormText name="id" label="id" placeholder="请输入名称" hidden={true} />
        <ProFormSelect
          name="itemName"
          label="检查项目"
          rules={[{ required: true, message: '请输入检查项目!' }]}
          disabled={createOrUpdate}
          options={checkOptions}
          fieldProps={{ onChange: handleMemoChange }}
        />
        <ProFormSelect
          name="itemDesc"
          label="检查描述"
          rules={[{ required: true, message: '请输入检查描述!' }]}
          disabled={createOrUpdate}
          options={descOptions}
        />
        {/* <Form.Item
            name="itemDesc"
            label="项目名称"
            rules={[{ required: true, message: '请选择项目!' }]}
          >
            <Select
              showSearch
              filterOption={filterOption}
              placeholder="请选择项目名称"
              options={projectOptions}
              disabled={editFlag}
              onChange={async (e) => {
                changeProjectCode(e);
              }}
            />
          </Form.Item> */}
        <ProFormText
          name="taskId"
          label="巡检任务号"
          rules={[{ required: true, message: '请输入巡检任务号!' }]}
          initialValue={currentTaskId}
          disabled={true}
        />
        <ProFormSelect
          name="itemResult"
          label="检查结果 正常/异常"
          /* fieldProps={{
            onChange: (value) => {
              setResultFlag(value);
              console.log('选择的正常异常：', value, '设置的', resultFlag);
            },
          }} */
          rules={[{ required: true, message: '请选择检查结果!' }]}
          disabled={createOrUpdate}
          options={[
            { value: 'true', label: '正常' },
            { value: 'false', label: '异常' },
          ]}
        />
        <ProFormText
          name="faultDesc"
          label="故障描述"
          disabled={createOrUpdate}
          rules={[{ required: false, message: '请输入故障描述!' }]}
        />
        <ProFormText name="notes" label="备注" disabled={createOrUpdate} hidden={true} />
        <ProFormText name="assignedTo" label="处理人" disabled={createOrUpdate} hidden={true} />
        <ProFormText name="attachment" label="附件" disabled={createOrUpdate} hidden={true} />
        <ProFormText name="deviceId" label="设备编号" disabled={createOrUpdate} hidden={true} />
        <ProFormText name="issue" label="问题描述" disabled={createOrUpdate} hidden={true} />
      </ModalForm>

      {/* 巡检任务明细附件明细查看提示框 */}
      <Modal
        visible={modalVisit1}
        title={'巡检任务明细详情'}
        width={1500}
        footer={[]}
        onCancel={() => {
          setModalVisit1(false);
          actionRef.current?.reload();
        }}
      >
        <Card>
          <Space direction="vertical" size="middle" style={{ display: 'flex' }}>
            <Descriptions title="" bordered column={2}>
              <Descriptions.Item label="检查描述">
                {inspectItem?.itemDesc ? inspectItem?.itemDesc : '-'}
              </Descriptions.Item>
              <Descriptions.Item label="检查项目">
                {inspectItem?.itemName ? inspectItem?.itemName : '-'}
              </Descriptions.Item>
              <Descriptions.Item label="巡检任务号">
                {inspectItem?.taskId ? inspectItem?.taskId : '-'}
              </Descriptions.Item>
              <Descriptions.Item label="检查结果">
                {inspectItem?.itemResult === 'true'
                  ? '正常'
                  : inspectItem?.itemResult === 'false'
                  ? '异常'
                  : '待检查'}
              </Descriptions.Item>
            </Descriptions>
          </Space>
        </Card>
        <Card>
          <ProTable
            headerTitle="巡检任务附件"
            actionRef={actionRef1} //用于触发刷新操作等，看api
            rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
            formRef={ref1}
            search={false}
            toolBarRender={(action, { selectedRows }) => [
              <Button
                key="button"
                icon={<PlusOutlined />}
                onClick={() => {
                  setCreateOrUpdate(false);
                  setFormTitle1('附件上传');
                  setModalVisit2(true);
                }}
                type="primary"
              >
                附件上传
              </Button>,
            ]}
            request={async (params, sort, filter) => {
              const paramFilter = {
                ...params,
                memo: inspectItem?.itemName,
                taskId: inspectItem?.taskId,
              };
              const sorters = sortTran(sort);
              const filters = filterTran(paramFilter);
              console.log(filters);
              const result = await getInspectFileByPage({
                ...params,
                sorters,
                filters,
              });
              console.log(result.data.content);
              return {
                data: result.data.content,
                total: result.data.totalElements,
                success: result.success,
              };
            }}
            columns={columns1}
            scroll={{ x: 800, y: 500 }}
            rowSelection={{}}
          />
        </Card>
      </Modal>

      {/* 巡检附件上传提示框 */}
      <ModalForm
        visible={modalVisit2}
        title={formTitle1}
        form={form}
        onFinish={addErrorFile}
        modalProps={{
          destroyOnClose: true,
          onCancel: () => {
            setModalVisit2(false);
          },
        }}
        initialValues={{
          taskId: inspectItem?.id,
        }}
      >
        <ProFormText
          name="taskId"
          label="巡检任务编号"
          disabled
          rules={[{ required: true, message: '请输入巡检任务编号!' }]}
        />

        <ProFormItem
          name="file"
          label="文件上传"
          rules={[{ required: true, message: '请选择上传的文件!' }]}
        >
          <Upload
            file-list="fileList"
            onChange={onFilesChange} //通过覆盖默认的上传行为，可以自定义自己的上传实现
            showUploadList={true}
            beforeUpload={handleBeforeUpload}
            multiple
          >
            <Button className="standProduct_UploadStyle" icon={<UploadOutlined />}>
              上传文件
            </Button>
          </Upload>
        </ProFormItem>
      </ModalForm>
    </PageHeaderWrapper>
  );
};
export default InspectItem;
